package model

import "sync"

// 用户组, 记录着所有用户
type userGroup struct {
	innerMap *sync.Map // Map<Long, User>
}

// 单例对象
var userGroupInstance = &userGroup{
	innerMap: &sync.Map{},
}

//
// GetUserGroup 获取用户组
func GetUserGroup() *userGroup {
	return userGroupInstance
}

//
// Add 添加用户到字典
func (group *userGroup) Add(user *User) {
	if nil == user {
		return
	}

	group.innerMap.Store(user.UserId, user)
}

//
// RemoveByUserId 删除用户
func (group *userGroup) RemoveByUserId(userId int64) {
	if userId <= 0 {
		return
	}

	group.innerMap.Delete(userId)
}

//
// GetByUserId 根据用户 Id 获取用户数据
func (group *userGroup) GetByUserId(userId int64) *User {
	if userId <= 0 {
		return nil
	}

	user, ok := group.innerMap.Load(userId)

	if !ok {
		return nil
	}

	return user.(*User)
}

//
// GetUserALL 获得所有用户
func (group *userGroup) GetUserALL() []*User {
	var userALL []*User

	group.innerMap.Range(func(k, v interface{}) bool {
		userALL = append(userALL, v.(*User))
		return true
	})

	return userALL
}
